<template>
  <PageLayout
    title="菜单权限管理"
    subtitle="管理角色的菜单访问权限"
    icon="fa fa-key"
    class="apply-glass-theme"
  >
    <template #toolbar-left>
      <el-button type="primary" @click="batchSetPermissions" class="tech-button">
        <i class="fa fa-users"></i> 批量设置权限
      </el-button>
      <el-button @click="refreshData" class="tech-button">
        <i class="fa fa-refresh"></i> 刷新
      </el-button>
    </template>

    <template #toolbar-right>
      <el-input
        v-model="searchText"
        placeholder="搜索角色..."
        clearable
        class="tech-input"
        style="width: 300px"
      >
        <template #prefix>
          <i class="fa fa-search"></i>
        </template>
      </el-input>
    </template>

    <template #content>
      <div class="permission-management-container">
        <!-- 角色选择卡片 -->
        <div class="role-selection-card glass-card">
          <div class="card-header">
            <div class="header-left">
              <i class="fa fa-user-tag header-icon"></i>
              <h3 class="card-title">角色选择</h3>
            </div>
            <div class="header-right">
              <el-tag v-if="selectedRole" type="primary" size="large" class="selected-role-tag">
                <i class="fa fa-check-circle"></i>
                {{ selectedRole.name }}
                <span class="role-type">{{ selectedRole.is_system ? '系统角色' : '自定义角色' }}</span>
              </el-tag>
            </div>
          </div>
          <div class="role-grid">
            <div
              v-for="role in filteredRoles"
              :key="role.id"
              :class="['role-card', { 'selected': selectedRole?.id === role.id }]"
              @click="selectRole(role)"
            >
              <div class="role-card-header">
                <div class="role-info">
                  <i class="fa fa-user-circle role-avatar"></i>
                  <div class="role-details">
                    <h4 class="role-name">{{ role.name }}</h4>
                    <p class="role-description">{{ role.description || '暂无描述' }}</p>
                  </div>
                </div>
                <div class="role-badges">
                  <el-tag :type="role.is_system ? 'warning' : 'success'" size="small" class="role-type-tag">
                    {{ role.is_system ? '系统' : '自定义' }}
                  </el-tag>
                  <el-tag type="info" size="small" class="permission-count-tag">
                    {{ role.permission_count || 0 }} 权限
                  </el-tag>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 权限配置卡片 -->
        <div class="permission-config-card glass-card" v-if="selectedRole">
          <div class="card-header">
            <div class="header-left">
              <i class="fa fa-sitemap header-icon"></i>
              <h3 class="card-title">菜单权限配置</h3>
              <div class="config-subtitle-container">
                <span class="config-subtitle">
                  为
                  <span class="role-highlight">"{{ selectedRole.name }}"</span>
                  配置菜单访问权限
                </span>
                <div class="subtitle-glow"></div>
              </div>
            </div>
            <div class="header-right">
              <div class="action-buttons">
                <el-button type="success" @click="savePermissions" class="permission-action-btn save-btn">
                  <i class="fa fa-save"></i> 保存权限
                </el-button>
                <el-button type="primary" @click="selectAllMenus" class="permission-action-btn select-all-btn">
                  <i class="fa fa-check-square"></i> 全选
                </el-button>
                <el-button type="warning" @click="clearAllMenus" class="permission-action-btn clear-btn">
                  <i class="fa fa-square-o"></i> 清空
                </el-button>
                <el-button @click="debugMenuData" class="permission-action-btn" type="info">
                  <i class="fa fa-bug"></i> 调试
                </el-button>
              </div>
            </div>
          </div>

          <div class="menu-tree-container">
            <el-tree
              ref="menuTreeRef"
              :data="menuTreeData"
              node-key="id"
              show-checkbox
              :props="{ label: 'label', children: 'children' }"
              :default-checked-keys="[]"
              :default-expanded-keys="expandedMenus"
              @check="handleMenuCheck"
              @node-expand="handleNodeExpand"
              @node-collapse="handleNodeCollapse"
              class="permission-tree"
            >
              <template #default="{ node, data }">
                <div class="tree-node-content">
                  <div class="menu-node-info">
                    <i :class="data.icon || 'fa fa-folder'" class="menu-icon"></i>
                    <div class="menu-details">
                      <div class="menu-name-row">
                        <span class="menu-name">{{ data.name }}</span>
                      </div>
                      <div class="menu-path-row" v-if="data.path">
                        <span class="menu-path">{{ data.path }}</span>
                      </div>
                    </div>
                  </div>
                  <div class="permission-controls" v-if="node.checked">
                    <el-tag
                      :type="getPermissionTagType(data.id)"
                      size="small"
                      class="permission-tag"
                    >
                      {{ getPermissionText(data.id) }}
                    </el-tag>
                    <el-button-group size="small" class="permission-buttons">
                      <el-button
                        :type="menuPermissions[data.id]?.can_read && !menuPermissions[data.id]?.can_write ? 'primary' : ''"
                        @click.stop="setPermissionLevel(data.id, 'read')"
                        size="small"
                        class="glass-button"
                      >
                        <i class="fa fa-eye"></i> 只读
                      </el-button>
                      <el-button
                        :type="menuPermissions[data.id]?.can_read && menuPermissions[data.id]?.can_write ? 'primary' : ''"
                        @click.stop="setPermissionLevel(data.id, 'write')"
                        size="small"
                        class="glass-button"
                      >
                        <i class="fa fa-edit"></i> 读写
                      </el-button>
                    </el-button-group>
                  </div>
                </div>
              </template>
            </el-tree>
          </div>
        </div>

        <!-- 空状态卡片 -->
        <div class="empty-state-card glass-card" v-else>
          <div class="empty-content">
            <i class="fa fa-hand-pointer-o empty-icon"></i>
            <h3 class="empty-title">请选择角色</h3>
            <p class="empty-description">选择上方的角色卡片来配置菜单权限</p>
          </div>
        </div>
      </div>
    </template>

    <template #dialogs>
      <!-- 批量设置权限对话框 -->
      <el-dialog
        v-model="batchDialogVisible"
        title="批量设置权限"
        width="800px"
        class="tech-dialog"
      >
        <div class="batch-permission-content">
          <div class="batch-section">
            <h4>选择角色</h4>
            <el-checkbox-group v-model="selectedRoles">
              <el-checkbox
                v-for="role in roles"
                :key="role.id"
                :label="role.id"
                :value="role.id"
              >
                {{ role.name }}
                <el-tag v-if="role.is_system" type="warning" size="small" style="margin-left: 5px;">系统</el-tag>
              </el-checkbox>
            </el-checkbox-group>
          </div>

          <div class="batch-section">
            <h4>选择菜单权限</h4>
            <div class="permission-level-selector">
              <span>权限级别：</span>
              <el-radio-group v-model="batchPermissionLevel">
                <el-radio value="read">只读</el-radio>
                <el-radio value="write">读写</el-radio>
              </el-radio-group>
            </div>
            <el-tree
              ref="batchMenuTreeRef"
              :data="menuTreeData"
              node-key="id"
              show-checkbox
              :props="{ label: 'name', children: 'children' }"
              class="menu-tree"
            >
              <template #default="{ node, data }">
                <div class="menu-node">
                  <div class="menu-info">
                    <i :class="data.icon || 'fa fa-folder'"></i>
                    <span class="menu-name">{{ data.name }}</span>
                    <span class="menu-path">{{ data.path }}</span>
                  </div>
                </div>
              </template>
            </el-tree>
          </div>
        </div>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="batchDialogVisible = false" class="tech-button">取消</el-button>
            <el-button type="primary" @click="executeBatchSet" class="tech-button">
              <i class="fa fa-save"></i> 批量设置
            </el-button>
          </div>
        </template>
      </el-dialog>
    </template>
  </PageLayout>
</template>

<script setup lang="ts">
import PageLayout from '@/components/PageLayout.vue'
import axios from 'axios'
import { ElMessage, ElMessageBox } from 'element-plus'
import { computed, nextTick, onMounted, ref } from 'vue'
import { STATIC_MENUS } from '@/config/menus'

// 响应式数据
const roleLoading = ref(false)
const roles = ref([])
const menus = ref([])
const selectedRole = ref(null)
const checkedMenus = ref([])
const expandedMenus = ref([])
const menuPermissions = ref({})
const searchText = ref('')
const menuTreeRef = ref()
const batchMenuTreeRef = ref()
const batchDialogVisible = ref(false)
const selectedRoles = ref([])
const batchPermissionLevel = ref('read')

// 计算属性
const filteredRoles = computed(() => {
  if (!searchText.value) return roles.value
  return roles.value.filter((role: any) =>
    role.name.toLowerCase().includes(searchText.value.toLowerCase()) ||
    (role.description && role.description.toLowerCase().includes(searchText.value.toLowerCase()))
  )
})

const menuTreeData = computed(() => {
  return buildMenuTree(menus.value)
})

// 方法
const fetchRoles = async () => {
  roleLoading.value = true
  try {
    const response = await axios.get('/api/roles/')
    roles.value = response.data.results || response.data
  } catch (error) {
    console.error('获取角色列表失败:', error)
    ElMessage.error('获取角色列表失败')
  } finally {
    roleLoading.value = false
  }
}

const fetchMenus = async () => {
  try {
    // 使用前端静态菜单配置，确保数据完整
    console.log('📋 使用静态菜单配置，菜单数量:', STATIC_MENUS.length)
    menus.value = STATIC_MENUS

    // 也可以尝试从后端获取，作为备用
    // const response = await axios.get('/api/menus/')
    // const backendMenus = response.data.results || response.data
    // console.log('🔄 后端菜单数量:', backendMenus.length)
  } catch (error) {
    console.error('获取菜单列表失败:', error)
    // 如果出错，使用静态菜单作为备用
    menus.value = STATIC_MENUS
    ElMessage.warning('使用本地菜单配置')
  }
}

const selectRole = async (role: any) => {
  selectedRole.value = role

  // 重置状态
  checkedMenus.value = []
  expandedMenus.value = []
  menuPermissions.value = {}

  // 获取权限数据
  await fetchRolePermissions(role.id)
}

const fetchRolePermissions = async (roleId: number) => {
  try {
    const response = await axios.get(`/api/roles/${roleId}/permissions/`)
    const permissions = response.data

    console.log('菜单权限管理 - 角色权限数据:', permissions)

    // 重置权限数据
    checkedMenus.value = []
    menuPermissions.value = {}

    // 将路径映射到菜单ID的函数
    const findMenuIdByPath = (menuList: any[], targetPath: string): string | null => {
      for (const menu of menuList) {
        if (menu.path === targetPath) {
          return menu.id || menu.path?.replace(/\//g, '-')
        }
        if (menu.children) {
          const found = findMenuIdByPath(menu.children, targetPath)
          if (found) return found
        }
      }
      return null
    }

    // 设置选中的菜单和权限
    permissions.forEach((perm: any) => {
      // 后端返回的数据中，menu_path是路径，menu_item是数字ID
      const menuPath = perm.menu_path || perm.menu_item  // 优先使用menu_path
      const menuId = findMenuIdByPath(menus.value, menuPath)

      console.log(`📋 权限映射: ${menuPath} -> ${menuId}`)
      console.log(`📋 权限数据:`, perm)

      if (menuId) {
        checkedMenus.value.push(menuId)
        menuPermissions.value[menuId] = {
          can_read: perm.can_read,
          can_write: perm.can_write
        }
      } else {
        console.warn(`⚠️  无法找到菜单: ${menuPath}`)
        console.warn(`⚠️  权限数据:`, perm)
      }
    })

    console.log('📋 最终选中的菜单IDs:', checkedMenus.value)
    console.log('📋 菜单权限配置:', menuPermissions.value)

    console.log('菜单权限管理 - 提取的菜单ID:', checkedMenus.value)
    console.log('菜单权限管理 - 权限配置:', menuPermissions.value)

    // 等待DOM更新后设置选中状态
    await nextTick()

    // 延迟设置选中状态，确保菜单树完全渲染
    setTimeout(async () => {
      if (menuTreeRef.value) {
        console.log('📋 开始设置菜单选中状态:', checkedMenus.value)

        // 先清空所有选中状态
        if (typeof menuTreeRef.value.setCheckedKeys === 'function') {
          menuTreeRef.value.setCheckedKeys([])
          console.log('📋 清空现有选中状态')
        }

        if (checkedMenus.value.length > 0) {
          // 先展开有选中子项的父菜单
          const expandKeys = []
          checkedMenus.value.forEach(menuId => {
            // 查找父菜单
            const findParent = (menuList: any[], targetId: string): string | null => {
              for (const menu of menuList) {
                if (menu.children) {
                  for (const child of menu.children) {
                    if (child.id === targetId) {
                      return menu.id
                    }
                  }
                  const found = findParent(menu.children, targetId)
                  if (found) return found
                }
              }
              return null
            }

            const parentId = findParent(menus.value, menuId)
            if (parentId && !expandKeys.includes(parentId)) {
              expandKeys.push(parentId)
            }
          })

          // 设置展开状态
          if (expandKeys.length > 0) {
            expandedMenus.value = expandKeys
            console.log('📋 自动展开父菜单:', expandKeys)
          }

          // 等待展开动画完成后设置选中状态
          await nextTick()
          setTimeout(() => {
            if (menuTreeRef.value && typeof menuTreeRef.value.setCheckedKeys === 'function') {
              menuTreeRef.value.setCheckedKeys(checkedMenus.value)
              console.log('✅ 菜单选中状态设置完成:', checkedMenus.value)

              // 验证设置结果
              setTimeout(() => {
                if (typeof menuTreeRef.value?.getCheckedKeys === 'function') {
                  const actualChecked = menuTreeRef.value.getCheckedKeys() || []
                  console.log('📋 验证选中状态:', actualChecked)
                  if (actualChecked.length !== checkedMenus.value.length) {
                    console.warn('⚠️  部分菜单选中失败')
                    console.log('📋 期望选中:', checkedMenus.value)
                    console.log('📋 实际选中:', actualChecked)
                  }
                }
              }, 100)
            } else {
              console.warn('⚠️  setCheckedKeys 方法不存在')
              if (menuTreeRef.value) {
                console.log('📋 Tree组件可用方法:', Object.getOwnPropertyNames(menuTreeRef.value))
              }
            }
          }, 300)
        } else {
          console.log('📋 没有需要选中的菜单')
        }
      } else {
        console.warn('⚠️  menuTreeRef 不存在')
      }
    }, 500)
  } catch (error) {
    console.error('获取角色权限失败:', error)
    checkedMenus.value = []
    menuPermissions.value = {}
  }
}

const handleMenuCheck = (data: any, checked: any) => {
  // 当菜单被选中或取消选中时，初始化权限
  const checkedKeys = checked.checkedKeys
  const halfCheckedKeys = checked.halfCheckedKeys

  console.log('📋 菜单选中事件:', {
    nodeData: data,
    checkedKeys,
    halfCheckedKeys,
    currentNodeChecked: checkedKeys.includes(data.id)
  })

  // 如果选中了有子菜单的节点，自动展开显示子菜单
  if (data.children && data.children.length > 0) {
    const isNodeChecked = checkedKeys.includes(data.id)
    const isNodeHalfChecked = halfCheckedKeys.includes(data.id)

    // 如果节点被选中或半选中，都展开子菜单
    if (isNodeChecked || isNodeHalfChecked) {
      if (!expandedMenus.value.includes(data.id)) {
        expandedMenus.value.push(data.id)
        console.log('📋 复选框触发 - 自动展开菜单:', data.name, data.id)

        // 立即更新树的展开状态
        nextTick(() => {
          // 暂时移除setExpandedKeys调用，因为可能不存在
          console.log('📋 复选框触发 - 更新展开状态:', expandedMenus.value)
        })
      }
    } else {
      // 如果节点被取消选中，检查是否需要折叠
      const index = expandedMenus.value.indexOf(data.id)
      if (index > -1) {
        // 检查子菜单是否还有选中的
        const hasCheckedChildren = data.children.some((child: any) => checkedKeys.includes(child.id))
        if (!hasCheckedChildren) {
          expandedMenus.value.splice(index, 1)
          console.log('📋 复选框触发 - 自动折叠菜单:', data.name, data.id)
          nextTick(() => {
            console.log('📋 复选框触发 - 更新折叠状态:', expandedMenus.value)
          })
        }
      }
    }
  }

  // 为新选中的菜单设置默认权限
  checkedKeys.forEach((menuId: string) => {
    if (!menuPermissions.value[menuId]) {
      menuPermissions.value[menuId] = {
        can_read: true,
        can_write: false
      }
    }
  })

  // 移除未选中菜单的权限
  Object.keys(menuPermissions.value).forEach(menuId => {
    if (!checkedKeys.includes(menuId)) {
      delete menuPermissions.value[menuId]
    }
  })
}

const handleNodeExpand = (data: any) => {
  if (!expandedMenus.value.includes(data.id)) {
    expandedMenus.value.push(data.id)
  }
}

const handleNodeCollapse = (data: any) => {
  const index = expandedMenus.value.indexOf(data.id)
  if (index > -1) {
    expandedMenus.value.splice(index, 1)
  }
}

const updateMenuPermission = (menuId: string, permType: string, value: boolean) => {
  if (!menuPermissions.value[menuId]) {
    menuPermissions.value[menuId] = { can_read: true, can_write: false }
  }
  menuPermissions.value[menuId][permType] = value
}

const setPermissionLevel = (menuId: string, level: 'read' | 'write') => {
  if (!menuPermissions.value[menuId]) {
    menuPermissions.value[menuId] = { can_read: true, can_write: false }
  }

  if (level === 'read') {
    menuPermissions.value[menuId].can_read = true
    menuPermissions.value[menuId].can_write = false
  } else if (level === 'write') {
    menuPermissions.value[menuId].can_read = true
    menuPermissions.value[menuId].can_write = true
  }
}

const getPermissionText = (menuId: string) => {
  const perm = menuPermissions.value[menuId]
  if (!perm || !perm.can_read) return '无权限'
  if (perm.can_read && perm.can_write) return '读写'
  if (perm.can_read && !perm.can_write) return '只读'
  return '无权限'
}

const getPermissionTagType = (menuId: string) => {
  const perm = menuPermissions.value[menuId]
  if (!perm || !perm.can_read) return 'info'
  if (perm.can_read && perm.can_write) return 'success'
  if (perm.can_read && !perm.can_write) return 'warning'
  return 'info'
}

const savePermissions = async () => {
  if (!selectedRole.value) return

  try {
    const checkedKeys = menuTreeRef.value?.getCheckedKeys() || []
    console.log('📋 保存权限 - 选中的菜单Keys:', checkedKeys)

    // 将菜单ID映射到路径，因为后端可能需要路径而不是ID
    const menuPermissionsList = checkedKeys.map((menuId: string) => {
      // 查找对应的菜单项
      const findMenuByIdOrPath = (menuList: any[], targetId: string): any => {
        for (const menu of menuList) {
          if (menu.id === targetId || menu.path?.replace(/\//g, '-') === targetId) {
            return menu
          }
          if (menu.children) {
            const found = findMenuByIdOrPath(menu.children, targetId)
            if (found) return found
          }
        }
        return null
      }

      const menuItem = findMenuByIdOrPath(menus.value, menuId)
      const menuPath = menuItem?.path || menuId

      return {
        menu_id: menuPath, // 使用路径作为菜单ID
        can_read: menuPermissions.value[menuId]?.can_read || true,
        can_write: menuPermissions.value[menuId]?.can_write || false
      }
    })

    console.log('📋 保存权限 - 权限列表:', menuPermissionsList)
    console.log('📋 保存权限 - 请求数据:', {
      menu_permissions: menuPermissionsList
    })

    const response = await axios.post(`/api/roles/${selectedRole.value.id}/set_permissions/`, {
      menu_permissions: menuPermissionsList
    })

    console.log('📋 保存权限 - 响应:', response.data)

    ElMessage.success('权限保存成功')

    // 更新角色的权限数量
    selectedRole.value.permission_count = checkedKeys.length

    // 刷新角色列表
    await fetchRoles()
  } catch (error) {
    console.error('保存权限失败:', error)
    ElMessage.error('保存权限失败')
  }
}

const selectAllMenus = () => {
  if (menuTreeRef.value) {
    const allKeys = getAllMenuKeys(menus.value)
    menuTreeRef.value.setCheckedKeys(allKeys)

    // 为所有菜单设置默认权限
    allKeys.forEach((menuId: string) => {
      menuPermissions.value[menuId] = {
        can_read: true,
        can_write: false
      }
    })
  }
}

const clearAllMenus = () => {
  if (menuTreeRef.value) {
    menuTreeRef.value.setCheckedKeys([])
    menuPermissions.value = {}
  }
}

const batchSetPermissions = () => {
  selectedRoles.value = []
  batchDialogVisible.value = true
}

const executeBatchSet = async () => {
  if (selectedRoles.value.length === 0) {
    ElMessage.warning('请选择要设置权限的角色')
    return
  }

  const checkedKeys = batchMenuTreeRef.value?.getCheckedKeys() || []
  if (checkedKeys.length === 0) {
    ElMessage.warning('请选择要分配的菜单权限')
    return
  }

  try {
    await ElMessageBox.confirm(
      `确定要为 ${selectedRoles.value.length} 个角色批量设置 ${checkedKeys.length} 个菜单权限吗？`,
      '确认批量设置',
      { type: 'warning' }
    )

    // 批量设置权限
    const promises = selectedRoles.value.map(roleId => {
      const menuPermissionsList = checkedKeys.map((menuId: string) => {
        // 查找对应的菜单项，与单个设置保持一致
        const findMenuByIdOrPath = (menuList: any[], targetId: string): any => {
          for (const menu of menuList) {
            if (menu.id === targetId || menu.path?.replace(/\//g, '-') === targetId) {
              return menu
            }
            if (menu.children) {
              const found = findMenuByIdOrPath(menu.children, targetId)
              if (found) return found
            }
          }
          return null
        }

        const menuItem = findMenuByIdOrPath(menus.value, menuId)
        const menuPath = menuItem?.path || menuId

        return {
          menu_id: menuPath, // 使用路径作为菜单ID，与单个设置保持一致
          can_read: true,
          can_write: batchPermissionLevel.value === 'write'
        }
      })

      console.log(`📋 批量设置 - 角色${roleId} - 权限列表:`, menuPermissionsList)

      return axios.post(`/api/roles/${roleId}/set_permissions/`, {
        menu_permissions: menuPermissionsList
      })
    })

    await Promise.all(promises)
    ElMessage.success('批量设置权限成功')
    batchDialogVisible.value = false

    // 刷新数据
    await fetchRoles()
    if (selectedRole.value) {
      await fetchRolePermissions(selectedRole.value.id)
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量设置权限失败:', error)
      ElMessage.error('批量设置权限失败')
    }
  }
}

const refreshData = async () => {
  await Promise.all([fetchRoles(), fetchMenus()])
  ElMessage.success('数据刷新成功')
}

const debugMenuData = () => {
  console.log('🔍 菜单数据调试信息:')
  console.log('='.repeat(50))
  console.log('📋 原始菜单数据:', menus.value)
  console.log('📋 处理后的菜单树:', menuTreeData.value)
  console.log('📋 当前选中的菜单:', checkedMenus.value)
  console.log('📋 菜单权限配置:', menuPermissions.value)
  console.log('📋 展开的菜单:', expandedMenus.value)

  if (menuTreeRef.value) {
    console.log('📋 树组件实际选中:', menuTreeRef.value.getCheckedKeys())
    console.log('📋 树组件展开状态:', menuTreeRef.value.getExpandedKeys())
  }

  // 验证菜单ID映射
  console.log('📋 菜单ID映射验证:')
  const allMenuIds = getAllMenuKeys(menus.value)
  console.log('📋 所有菜单ID:', allMenuIds)

  // 检查是否有重复ID
  const duplicates = allMenuIds.filter((id, index) => allMenuIds.indexOf(id) !== index)
  if (duplicates.length > 0) {
    console.warn('⚠️  发现重复的菜单ID:', duplicates)
  } else {
    console.log('✅ 菜单ID无重复')
  }

  ElMessage.info('调试信息已输出到控制台')
}

const buildMenuTree = (menus: any[]) => {
  // 静态菜单配置已经是树形结构，直接返回
  // 但需要确保每个菜单项都有唯一的ID用于权限管理
  const processMenu = (menu: any, parentId?: string): any => {
    const processedMenu = {
      ...menu,
      // 如果没有ID，使用路径生成ID
      id: menu.id || menu.path?.replace(/\//g, '-') || Math.random().toString(36).substr(2, 9),
      label: menu.name,
      children: menu.children ? menu.children.map((child: any) => processMenu(child, menu.id)) : []
    }
    return processedMenu
  }

  return menus.map(menu => processMenu(menu))
}

const getAllMenuKeys = (menus: any[]): string[] => {
  const keys: string[] = []

  const extractKeys = (menuList: any[]) => {
    menuList.forEach(menu => {
      // 添加当前菜单的ID
      const menuId = menu.id || menu.path?.replace(/\//g, '-')
      if (menuId) {
        keys.push(menuId)
      }

      // 递归处理子菜单
      if (menu.children && menu.children.length > 0) {
        extractKeys(menu.children)
      }
    })
  }

  extractKeys(menus)
  return keys
}

// 生命周期
onMounted(() => {
  fetchRoles()
  fetchMenus()
})
</script>

<style scoped>
/* 透明玻璃按钮样式 */
:deep(.el-button) {
  background: rgba(255, 255, 255, 0.05) !important;
  border: 1px solid rgba(255, 255, 255, 0.1) !important;
  color: rgba(255, 255, 255, 0.9) !important;
  backdrop-filter: blur(10px) !important;
  transition: all 0.3s ease !important;
  border-radius: 8px !important;
  font-weight: 500 !important;

  &:hover {
    background: rgba(255, 255, 255, 0.1) !important;
    border-color: rgba(0, 234, 255, 0.3) !important;
    transform: translateY(-1px) !important;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2) !important;
    color: #ffffff !important;
  }

  &.el-button--primary {
    background: linear-gradient(135deg, rgba(0, 234, 255, 0.8), rgba(0, 153, 204, 0.8)) !important;
    border-color: rgba(0, 234, 255, 0.6) !important;
    color: #ffffff !important;
    box-shadow: 0 4px 15px rgba(0, 234, 255, 0.3) !important;

    &:hover {
      background: linear-gradient(135deg, rgba(51, 240, 255, 0.9), rgba(0, 184, 230, 0.9)) !important;
      box-shadow: 0 6px 20px rgba(0, 234, 255, 0.4) !important;
    }
  }

  &.el-button--success {
    background: linear-gradient(135deg, rgba(103, 194, 58, 0.8), rgba(85, 170, 85, 0.8)) !important;
    border-color: rgba(103, 194, 58, 0.6) !important;
    color: #ffffff !important;
    box-shadow: 0 4px 15px rgba(103, 194, 58, 0.3) !important;

    &:hover {
      background: linear-gradient(135deg, rgba(129, 212, 85, 0.9), rgba(108, 186, 108, 0.9)) !important;
      box-shadow: 0 6px 20px rgba(103, 194, 58, 0.4) !important;
    }
  }
}

/* 主容器样式 */
.permission-management-container {
  display: flex;
  flex-direction: column;
  gap: 24px;
  padding: 0;
}

/* 强制应用玻璃卡片基础样式 */
.glass-card,
:deep(.glass-card),
.role-selection-card,
.permission-config-card,
.empty-state-card {
  background: rgba(255, 255, 255, 0.02) !important;
  border: 1px solid rgba(255, 255, 255, 0.08) !important;
  backdrop-filter: blur(20px) saturate(150%) !important;
  -webkit-backdrop-filter: blur(20px) saturate(150%) !important;
  border-radius: 16px !important;
  padding: 24px !important;
  box-shadow:
    0 8px 32px rgba(0, 0, 0, 0.3),
    inset 0 1px 0 rgba(255, 255, 255, 0.1) !important;
  position: relative !important;
  overflow: hidden !important;
}

/* 确保容器背景透明 */
.permission-management-container {
  background: transparent !important;
}

/* 角色选择卡片特定样式（继承玻璃效果） */

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 16px;
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
}

.header-left {
  display: flex;
  align-items: center;
  gap: 12px;
}

.header-icon {
  font-size: 24px;
  color: #00eaff;
  text-shadow: 0 0 10px rgba(0, 234, 255, 0.5);
}

.card-title {
  margin: 0;
  font-size: 20px;
  font-weight: 600;
  color: #ffffff;
  text-shadow: 0 0 10px rgba(255, 255, 255, 0.3);
}

.config-subtitle-container {
  position: relative;
  margin-left: 16px;
  display: inline-block;
  padding: 8px 16px;
  background: rgba(255, 255, 255, 0.03);
  border: 1px solid rgba(0, 234, 255, 0.2);
  border-radius: 12px;
  backdrop-filter: blur(10px);
  transition: all 0.3s ease;
  cursor: pointer;

  &:hover {
    background: rgba(255, 255, 255, 0.05);
    border-color: rgba(0, 234, 255, 0.4);
    transform: translateY(-1px);
    box-shadow:
      0 4px 15px rgba(0, 234, 255, 0.2),
      0 2px 8px rgba(0, 0, 0, 0.1);
  }

  &:active {
    transform: translateY(0);
    box-shadow:
      0 2px 8px rgba(0, 234, 255, 0.3),
      inset 0 2px 4px rgba(0, 0, 0, 0.1);
  }
}

.config-subtitle {
  font-size: 14px;
  color: rgba(255, 255, 255, 0.9);
  font-weight: 500;
  text-shadow: 0 0 10px rgba(255, 255, 255, 0.3);
  position: relative;
  z-index: 2;
  margin: 0;
  line-height: 1.4;
}

.role-highlight {
  color: #00eaff;
  font-weight: 600;
  text-shadow: 0 0 15px rgba(0, 234, 255, 0.6);
  background: linear-gradient(135deg, #00eaff, #33f0ff);
  background-clip: text;
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  animation: roleGlow 2s ease-in-out infinite alternate;
  position: relative;
}

@keyframes roleGlow {
  0% {
    text-shadow: 0 0 15px rgba(0, 234, 255, 0.6);
    filter: brightness(1);
  }
  100% {
    text-shadow: 0 0 25px rgba(0, 234, 255, 0.9), 0 0 35px rgba(0, 234, 255, 0.5);
    filter: brightness(1.2);
  }
}

.subtitle-glow {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 100%;
  height: 2px;
  background: linear-gradient(90deg, transparent, rgba(0, 234, 255, 0.3), transparent);
  border-radius: 1px;
  z-index: 1;
  animation: subtitleFlow 3s ease-in-out infinite;
}

@keyframes subtitleFlow {
  0%, 100% {
    opacity: 0;
    transform: translate(-50%, -50%) scaleX(0);
  }
  50% {
    opacity: 1;
    transform: translate(-50%, -50%) scaleX(1);
  }
}

.selected-role-tag {
  background: linear-gradient(135deg, rgba(0, 234, 255, 0.8), rgba(0, 153, 204, 0.8)) !important;
  border: none !important;
  color: #ffffff !important;
  padding: 8px 16px !important;
  border-radius: 20px !important;
  font-weight: 500 !important;
  box-shadow: 0 4px 15px rgba(0, 234, 255, 0.3) !important;

  .role-type {
    margin-left: 8px;
    opacity: 0.8;
    font-size: 12px;
  }
}

/* 角色网格布局 */
.role-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 16px;
  max-height: 400px;
  overflow-y: auto;
  padding: 4px;
}

.role-card {
  background: rgba(255, 255, 255, 0.03);
  border: 1px solid rgba(255, 255, 255, 0.1);
  border-radius: 12px;
  padding: 16px;
  cursor: pointer;
  transition: all 0.3s ease;
  backdrop-filter: blur(10px);

  &:hover {
    background: rgba(255, 255, 255, 0.06);
    border-color: rgba(0, 234, 255, 0.3);
    transform: translateY(-2px);
    box-shadow: 0 8px 25px rgba(0, 0, 0, 0.2);
  }

  &.selected {
    background: rgba(0, 234, 255, 0.1);
    border-color: rgba(0, 234, 255, 0.5);
    box-shadow: 0 0 20px rgba(0, 234, 255, 0.3);
  }
}

.role-card-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
}

.role-info {
  display: flex;
  align-items: flex-start;
  gap: 12px;
  flex: 1;
}

.role-avatar {
  font-size: 32px;
  color: #00eaff;
  text-shadow: 0 0 10px rgba(0, 234, 255, 0.5);
}

.role-details {
  flex: 1;
}

.role-name {
  margin: 0 0 4px 0;
  font-size: 16px;
  font-weight: 600;
  color: #ffffff;
}

.role-description {
  margin: 0;
  font-size: 12px;
  color: rgba(255, 255, 255, 0.6);
  line-height: 1.4;
}

.role-badges {
  display: flex;
  flex-direction: column;
  gap: 6px;
  align-items: flex-end;
}

.role-type-tag,
.permission-count-tag {
  font-size: 11px !important;
  padding: 2px 8px !important;
  border-radius: 12px !important;
}

/* 权限配置卡片特定样式（继承玻璃效果） */

.action-buttons {
  display: flex;
  gap: 16px;
}

/* 权限操作按钮专用样式 */
.permission-action-btn {
  min-width: 120px !important;
  height: 40px !important;
  padding: 0 20px !important;
  font-size: 14px !important;
  font-weight: 600 !important;
  border-radius: 10px !important;
  background: rgba(255, 255, 255, 0.05) !important;
  border: 1px solid rgba(255, 255, 255, 0.1) !important;
  color: rgba(255, 255, 255, 0.9) !important;
  backdrop-filter: blur(10px) !important;
  transition: all 0.3s ease !important;
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1) !important;

  i {
    font-size: 14px !important;
    margin-right: 8px !important;
  }

  &:hover {
    background: rgba(255, 255, 255, 0.1) !important;
    border-color: rgba(0, 234, 255, 0.3) !important;
    transform: translateY(-2px) !important;
    box-shadow: 0 8px 25px rgba(0, 0, 0, 0.2) !important;
    color: #ffffff !important;
  }

  &.el-button--success {
    background: linear-gradient(135deg, rgba(103, 194, 58, 0.8), rgba(85, 170, 85, 0.8)) !important;
    border-color: rgba(103, 194, 58, 0.6) !important;
    color: #ffffff !important;
    box-shadow: 0 4px 15px rgba(103, 194, 58, 0.3) !important;

    &:hover {
      background: linear-gradient(135deg, rgba(129, 212, 85, 0.9), rgba(108, 186, 108, 0.9)) !important;
      box-shadow: 0 8px 25px rgba(103, 194, 58, 0.4) !important;
      border-color: rgba(103, 194, 58, 0.8) !important;
    }
  }

  &.el-button--warning {
    background: linear-gradient(135deg, rgba(255, 193, 7, 0.8), rgba(255, 152, 0, 0.8)) !important;
    border-color: rgba(255, 193, 7, 0.6) !important;
    color: #ffffff !important;
    box-shadow: 0 4px 15px rgba(255, 193, 7, 0.3) !important;

    &:hover {
      background: linear-gradient(135deg, rgba(255, 206, 84, 0.9), rgba(255, 167, 38, 0.9)) !important;
      box-shadow: 0 8px 25px rgba(255, 193, 7, 0.4) !important;
      border-color: rgba(255, 193, 7, 0.8) !important;
    }
  }
}

/* 菜单树容器样式 */
.menu-tree-container {
  max-height: 600px;
  overflow-y: auto;
  padding: 16px;
  background: rgba(255, 255, 255, 0.02) !important;
  border: 1px solid rgba(255, 255, 255, 0.08) !important;
  backdrop-filter: blur(20px) saturate(150%) !important;
  -webkit-backdrop-filter: blur(20px) saturate(150%) !important;
  border-radius: 16px !important;
  box-shadow:
    0 8px 32px rgba(0, 0, 0, 0.3),
    inset 0 1px 0 rgba(255, 255, 255, 0.1) !important;
}

/* 权限树样式 */
:deep(.permission-tree) {
  background: transparent !important;
  color: #ffffff !important;

  .el-tree-node__content {
    background: transparent !important;
    border-radius: 8px !important;
    margin: 4px 0 !important;
    padding: 12px 16px !important;
    transition: all 0.3s ease !important;
    min-height: 60px !important;

    &:hover {
      background: rgba(255, 255, 255, 0.05) !important;
    }
  }

  .el-tree-node__expand-icon {
    color: #00eaff !important;
  }

  .el-checkbox__input.is-checked .el-checkbox__inner {
    background-color: #00eaff !important;
    border-color: #00eaff !important;
  }

  .el-checkbox__inner {
    border-color: rgba(255, 255, 255, 0.3) !important;
    background: rgba(255, 255, 255, 0.05) !important;
  }
}

.tree-node-content {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  width: 100%;
  min-height: 50px;
  padding: 8px 0;
  gap: 16px;
}

.menu-node-info {
  display: flex;
  align-items: center;
  gap: 12px;
  flex: 1;
}

.menu-icon {
  font-size: 16px;
  color: #00eaff;
  width: 20px;
  text-align: center;
}

.menu-details {
  display: flex;
  flex-direction: column;
  gap: 4px;
  flex: 1;
  min-width: 0; /* 允许内容收缩 */
}

.menu-name-row {
  display: flex;
  align-items: center;
}

.menu-name {
  font-size: 14px;
  font-weight: 500;
  color: #ffffff;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.menu-path-row {
  display: flex;
  align-items: center;
  margin-top: 2px;
}

.menu-path {
  font-size: 11px;
  color: rgba(255, 255, 255, 0.5);
  background: rgba(0, 234, 255, 0.1);
  padding: 2px 6px;
  border-radius: 10px;
  border: 1px solid rgba(0, 234, 255, 0.2);
  font-family: 'Courier New', monospace;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  max-width: 200px;
}

.permission-controls {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  gap: 6px;
  min-width: 160px;
  flex-shrink: 0;
}

.permission-tag {
  font-size: 11px !important;
  padding: 2px 8px !important;
  border-radius: 12px !important;
}

.permission-buttons {
  display: flex;
  gap: 4px;

  .el-button {
    font-size: 11px !important;
    padding: 4px 8px !important;
    height: 26px !important;
    min-width: 50px !important;
    border-radius: 6px !important;
  }
}

/* 空状态卡片特定样式（继承玻璃效果） */
.empty-state-card {
  padding: 60px 24px !important;
  text-align: center !important;
}

.empty-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 16px;
}

.empty-icon {
  font-size: 48px;
  color: rgba(255, 255, 255, 0.3);
}

.empty-title {
  margin: 0;
  font-size: 18px;
  color: #ffffff;
}

.empty-description {
  margin: 0;
  font-size: 14px;
  color: rgba(255, 255, 255, 0.6);
}

/* 批量设置对话框样式 */
.batch-permission-content {
  display: flex;
  flex-direction: column;
  gap: 24px;
}

.batch-section h4 {
  margin: 0 0 12px 0;
  color: #00eaff;
  font-size: 16px;
  font-weight: 600;
}

.permission-level-selector {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 16px;
  padding: 12px 16px;
  background: rgba(0, 234, 255, 0.1);
  border-radius: 8px;
  border: 1px solid rgba(0, 234, 255, 0.3);

  span {
    color: #00eaff;
    font-weight: 500;
  }
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  margin-top: 24px;
}

/* 滚动条样式 */
.role-grid::-webkit-scrollbar,
.menu-tree-container::-webkit-scrollbar {
  width: 6px;
}

.role-grid::-webkit-scrollbar-track,
.menu-tree-container::-webkit-scrollbar-track {
  background: rgba(255, 255, 255, 0.05);
  border-radius: 3px;
}

.role-grid::-webkit-scrollbar-thumb,
.menu-tree-container::-webkit-scrollbar-thumb {
  background: rgba(0, 234, 255, 0.3);
  border-radius: 3px;

  &:hover {
    background: rgba(0, 234, 255, 0.5);
  }
}

/* 透明玻璃弹窗样式 */
:deep(.el-dialog) {
  background: rgba(255, 255, 255, 0.02) !important;
  border: 1px solid rgba(255, 255, 255, 0.08) !important;
  backdrop-filter: blur(20px) saturate(150%) !important;
  border-radius: 16px !important;
  box-shadow:
    0 8px 32px rgba(0, 0, 0, 0.3),
    inset 0 1px 0 rgba(255, 255, 255, 0.1) !important;

  .el-dialog__header {
    background: transparent !important;
    border-bottom: 1px solid rgba(255, 255, 255, 0.1) !important;
    padding: 20px 24px 16px 24px !important;

    .el-dialog__title {
      color: #ffffff !important;
      font-size: 18px !important;
      font-weight: 600 !important;
      text-shadow: 0 0 10px rgba(255, 255, 255, 0.3) !important;
    }

    .el-dialog__headerbtn {
      .el-dialog__close {
        color: rgba(255, 255, 255, 0.7) !important;
        font-size: 18px !important;

        &:hover {
          color: #ff4757 !important;
        }
      }
    }
  }

  .el-dialog__body {
    background: transparent !important;
    padding: 24px !important;
    color: #ffffff !important;
  }

  .el-dialog__footer {
    background: transparent !important;
    border-top: 1px solid rgba(255, 255, 255, 0.1) !important;
    padding: 16px 24px 20px 24px !important;
  }
}

/* 表单样式优化 */
:deep(.el-form-item__label) {
  color: rgba(255, 255, 255, 0.9) !important;
  font-weight: 500 !important;
}

:deep(.el-checkbox) {
  .el-checkbox__label {
    color: rgba(255, 255, 255, 0.9) !important;
  }

  .el-checkbox__input.is-checked .el-checkbox__inner {
    background-color: #00eaff !important;
    border-color: #00eaff !important;
  }

  .el-checkbox__inner {
    border-color: rgba(255, 255, 255, 0.3) !important;
    background: rgba(255, 255, 255, 0.05) !important;
  }
}

:deep(.el-radio) {
  .el-radio__label {
    color: rgba(255, 255, 255, 0.9) !important;
  }

  .el-radio__input.is-checked .el-radio__inner {
    background-color: #00eaff !important;
    border-color: #00eaff !important;
  }

  .el-radio__inner {
    border-color: rgba(255, 255, 255, 0.3) !important;
    background: rgba(255, 255, 255, 0.05) !important;
  }
}
</style>
